<template>
    <fieldset>
        <h1>{{ content }}</h1>
        <button v-for="(item, index) in buttons" :key="index" @click="handleClick(index + 1)"
            :class="{ active: nowPage === index + 1 }">
            {{ item }}
        </button>
    </fieldset>
</template>
<script setup>
import { reactive, ref, onMounted, watchEffect } from 'vue';
import CancelPromise from './cancelPromise.js';


let buttons = reactive(['第一页', '第二页', '第三页'])

let api1 = (signal) => new CancelPromise((resolve, reject) => {
    setTimeout(() => {
        resolve('第一页数据')
    }, 1000)
},signal)
let api2 = (signal) => new CancelPromise((resolve, reject) => {
    setTimeout(() => {
        resolve('第二页数据')
    }, 2000)
},signal)
let api3 = (signal) => new CancelPromise((resolve, reject) => {
    setTimeout(() => {
        resolve('第三页数据')
    }, 3000)
},signal)


let api = {
    api1,
    api2,
    api3
}


let content = ref('')
let nowPage = ref(1)

//1.点击按钮触发的处理函数
let handleClick = (pageNum) => {
    // fetchData(pageNum)
    nowPage.value = pageNum
}

//2.处理函数会修改这个响应式状态
//封装一个获取内容的方法
/**
 * 
 * @param {Number} pageNum 传递给后台的页码
 */
 //4.调用api接口获取数据
let fetchData = (pageNum,signal) => {
    console.log(pageNum);
    return api['api' + pageNum](signal)
        .then(res => {
            console.log(res);
            content.value = res
        })
}

//3.会侦听 第2步的状态， 如果状态改变 就会触发里面的函数;里面的函数执行了4方法
watchEffect(invalidate => {
    console.log(nowPage.value);
    let abortController = new AbortController();

    let signal = abortController.signal
    fetchData(nowPage.value,signal)
    invalidate(() => {
        //页面切换之前,取消上一个promise
        abortController.abort()
    })
})



// onMounted(() => {
//     nowPage.value = 1
// })


</script>
<style>
.active {
    background-color: pink;
}
</style>